package com.example.chatroom.controller;

import com.example.chatroom.model.Message;
import com.example.chatroom.repository.ChatMessageRepository;
import com.example.chatroom.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import org.springframework.messaging.handler.annotation.SendTo;
import java.time.LocalDateTime;
import org.springframework.context.event.EventListener;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import java.util.Set;

@Controller
public class ChatController {
    
    @Autowired
    private SimpMessageSendingOperations messagingTemplate;
    
    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    @SuppressWarnings("unused")
    private ChatService chatService;

    @MessageMapping("/chat.register")
    @SendTo("/topic/public")
    public Message register(@Payload Message message, SimpMessageHeaderAccessor headerAccessor) {
        // 获取sessionId并保存用户信息
        String sessionId = headerAccessor.getSessionId();
        chatService.addUser(sessionId, message.getSender());
        
        // 广播用户列表更新
        messagingTemplate.convertAndSend("/topic/users", chatService.getOnlineUsers());
        
        message.setTimestamp(LocalDateTime.now());
        return message;
    }

    @MessageMapping("/chat.send")
    @SendTo("/topic/public")
    public Message sendMessage(@Payload Message message) {
        try {
            // 设置消息时间戳
            message.setTimestamp(LocalDateTime.now());
            
            // 如果是私聊消息
            if (message.getReceiver() != null && !message.getReceiver().isEmpty()) {
                messagingTemplate.convertAndSendToUser(
                    message.getReceiver(),
                    "/queue/private",
                    message
                );
                messagingTemplate.convertAndSendToUser(
                    message.getSender(),
                    "/queue/private",
                    message
                );
                chatMessageRepository.save(message);
                return null;
            }
            
            // 如果是文件消息，直接保存并广播
            if ("FILE".equals(message.getType())) {
                // 从content中提取文件名（如果没有在别处设置的话）
                if (message.getFileName() == null && message.getContent() != null) {
                    int lastIndex = message.getContent().lastIndexOf('/');
                    if (lastIndex >= 0) {
                        message.setFileName(message.getContent().substring(lastIndex + 1));
                    }
                }
                chatMessageRepository.save(message);
                return message;
            }
            
            // 普通消息处理
            chatMessageRepository.save(message);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            Message errorMessage = new Message();
            errorMessage.setType("ERROR");
            errorMessage.setContent("消息发送失败: " + e.getMessage());
            return errorMessage;
        }
    }

    @MessageMapping("/chat.heartbeat")
    public void processHeartbeat(@Payload Message message) {
        // 处理心跳消息
    }

    // 添加用户列表请求处理
    @MessageMapping("/chat.users")
    @SendTo("/topic/users")
    public Set<String> getUsers() {
        return chatService.getOnlineUsers();
    }

    // 添加用户断开连接的处理
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        String sessionId = event.getSessionId();
        String username = chatService.getUser(sessionId);
        
        if (username != null) {
            chatService.removeUser(sessionId);
            
            // 发送用户离开消息
            Message message = new Message();
            message.setType("LEAVE");
            message.setSender(username);
            message.setTimestamp(LocalDateTime.now());
            messagingTemplate.convertAndSend("/topic/public", message);
            
            // 广播更新后的用户列表
            messagingTemplate.convertAndSend("/topic/users", chatService.getOnlineUsers());
        }
    }

    @MessageMapping("/chat.username")
    @SendTo("/topic/public")
    public Message updateUsername(@Payload Message message, SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = headerAccessor.getSessionId();
        String oldUsername = chatService.getUser(sessionId);
        String newUsername = message.getContent();
        
        if (oldUsername != null && newUsername != null) {
            chatService.updateUsername(sessionId, newUsername);
            
            // 发送用户名更新消息
            message.setType("USERNAME_CHANGE");
            message.setSender(oldUsername);
            message.setContent(newUsername);
            message.setTimestamp(LocalDateTime.now());
            
            // 广播更新后的用户列表
            messagingTemplate.convertAndSend("/topic/users", chatService.getOnlineUsers());
            
            return message;
        }
        return null;
    }
} 